package com.logistics.controller;

import com.logistics.common.Result;
import com.logistics.entity.LogisticsOrder;
import com.logistics.entity.User;
import com.logistics.service.LogisticsOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/logistics-order")
public class LogisticsOrderController {
    @Autowired
    private LogisticsOrderService logisticsOrderService;

    @PostMapping
    public Result createOrder(@RequestBody LogisticsOrder order, HttpSession session) {
        // 从session中获取用户对象
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.fail("用户未登录");
        }
        order.setUserId(user.getId());
        return logisticsOrderService.createOrder(order);
    }

    @GetMapping("/{id}")
    public Result<LogisticsOrder> getById(@PathVariable Long id) {
        return logisticsOrderService.getOrder(id);
    }

    @GetMapping("/no/{orderNo}")
    public Result<LogisticsOrder> getByOrderNo(@PathVariable String orderNo) {
        return logisticsOrderService.getOrderByOrderNo(orderNo);
    }

    @GetMapping("/list")
    public Result<List<Map<String, Object>>> list() {
        return logisticsOrderService.listOrders();
    }

    @PutMapping
    public Result<LogisticsOrder> update(@RequestBody LogisticsOrder order) {
        return logisticsOrderService.updateOrder(order);
    }

    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        return logisticsOrderService.deleteOrder(id);
    }

    @PutMapping("/{id}/status/{status}")
    public Result<LogisticsOrder> updateStatus(@PathVariable Long id, @PathVariable String status) {
        return logisticsOrderService.updateOrderStatus(id, status);
    }

    @GetMapping("/search")
    public Result<List<Map<String, Object>>> search(
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        return logisticsOrderService.searchOrders(orderNo, status, startDate, endDate);
    }
} 